﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TheoriesBraun.BLL;
using TheoriesBraun.DAL;
using System.IO;
using System.Data.SqlClient;

namespace TheoriesBraun
{
    public partial class Management : Form
    {
        DataView dv = null;
        UserDAL udal = null;
        UserBLL ubll = null;
        TheoriesDAL tdal = null;
        TheoriesBLL tbll = null;
        QuestionDAL qdal = null;
        QuestionBLL qbll = null;
        Validates check = new Validates();
        OpenFileDialog _openFileDialog = new OpenFileDialog();
        SqlDataAdapter adapter;
        BindingSource bs = new BindingSource();

        public Management()
        {
            InitializeComponent();
            userBiding();
            theoriesBiding();
            questionBiding();
            loadCbxTheories();
        }

        public void userBiding()
        {
            udal = new UserDAL();
            dv = new DataView(udal.getAllUser());
            dgvUsers.DataSource = dv;
            lblURecord.Text = dgvUsers.RowCount.ToString();
        }

        public void theoriesBiding()
        {
            tdal = new TheoriesDAL();
            dv = new DataView(tdal.getAllTheories());
            dgvTheories.DataSource = dv;
            lblTRecord.Text = dgvTheories.RowCount.ToString();
        }

        public void questionBiding()
        {
            qdal = new QuestionDAL();
            dv = new DataView(qdal.getAllQuestion());
            dgvQuestion.DataSource = dv;
            lblQRecord.Text = dgvQuestion.RowCount.ToString();
        }

        public void loadCbxTheories() 
        {
            tdal = new TheoriesDAL();
            dv = new DataView(tdal.loadTheoryList());
            cbxLoadChapter.DataSource = dv;
            cbxLoadChapter.DisplayMember = "Chapter";
            cbxLoadChapter.ValueMember = "ChapterAndName";
        }

        private void rbMQ_MouseClick(object sender, MouseEventArgs e)
        {
            panelMQ.Visible = true;
        }

        private void rbNQ_MouseClick(object sender, MouseEventArgs e)
        {
            panelMQ.Visible = false;
        }

        private void btnChooseQuestion_Click(object sender, EventArgs e)
        {
            try
            {
                _openFileDialog.Title = "Open Media Question file";
                _openFileDialog.InitialDirectory = @"C:\";//Thư mục mặc định khi mở
                _openFileDialog.Filter = "MP3 (*.mp3)|*.mp3|WMA (*.WMA)|*.WMA|WAV (*.WAV)|*.WAV|All files (*.*)|*.*";// Lọc ra những file cần hiển thị
                _openFileDialog.RestoreDirectory = true;

                if (_openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string[] tmp = _openFileDialog.FileNames;

                    foreach (string i in tmp)
                    {
                        FileInfo fileInfo = new FileInfo(i);
                        string[] xxx = i.Split('\\');
                        string des = Application.StartupPath + @"\Files\Questions\" + xxx[xxx.Length - 1];
                        File.Delete(des);

                        txtQFile.Text = xxx[xxx.Length - 1];
                        fileInfo.CopyTo(des);
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void btnChooseAnswer_Click(object sender, EventArgs e)
        {
            try
            {
                _openFileDialog.Title = "Open Media Question file";
                _openFileDialog.InitialDirectory = @"C:\";//Thư mục mặc định khi mở
                _openFileDialog.Filter = "MP3 (*.mp3)|*.mp3|WMA (*.WMA)|*.WMA|WAV (*.WAV)|*.WAV|All files (*.*)|*.*";// Lọc ra những file cần hiển thị
                _openFileDialog.RestoreDirectory = true;

                if (_openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string[] tmp = _openFileDialog.FileNames;

                    foreach (string i in tmp)
                    {
                        FileInfo fileInfo = new FileInfo(i);
                        string[] xxx = i.Split('\\');
                        string des = Application.StartupPath + @"\Files\Answers\" + xxx[xxx.Length - 1];
                        File.Delete(des);

                        txtQAFile.Text = xxx[xxx.Length - 1];
                        fileInfo.CopyTo(des);
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void linkLogout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Login loginForm = new Login();
            this.Close();
            loginForm.Show();
        }

        private void btnUCreate_Click(object sender, EventArgs e)
        {
            udal = new UserDAL();
            ubll = new UserBLL();

            try
            {
                ubll.FullName = txtFullName.Text;
                ubll.Account = txtAccount.Text;
                ubll.Password = txtPass.Text;
                ubll.Email = txtEmail.Text;
                ubll.Phone = txtPhone.Text;
                ubll.Address = txtAddress.Text;
                ubll.Status = Int32.Parse(cbxStatus.SelectedIndex.ToString()) + 1;

                if (ubll.FullName.Equals("") == false && ubll.Account.Equals("") == false && ubll.Password.Equals("") == false && ubll.Address.Equals("") == false && ubll.Phone.Equals("") == false && ubll.Email.Equals("") == false)
                {
                    if (check.IsAlphaNumeric(ubll.Account) && check.IsAlphaNumeric(ubll.Password) && ubll.Password.Length >= 4)
                    {
                        if (check.IsValidEmail(ubll.Email))
                        {
                            udal.addUser(ubll);
                            MessageBox.Show("An user have been created successfully!");
                            userBiding();
                        }
                        else
                        {
                            MessageBox.Show("Email is invalid!");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Account or Password is invalid!");
                    }
                }
                else
                {
                    MessageBox.Show("You don't enter complete information!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnUUpdate_Click(object sender, EventArgs e)
        {
            udal = new UserDAL();
            ubll = new UserBLL();

            try
            {
                ubll.FullName = txtFullName.Text;
                ubll.Account = txtAccount.Text;
                ubll.Password = txtPass.Text;
                ubll.Email = txtEmail.Text;
                ubll.Phone = txtPhone.Text;
                ubll.Address = txtAddress.Text;
                ubll.Status = Int32.Parse(cbxStatus.SelectedIndex.ToString()) + 1;

                if (MessageBox.Show("You sure you want to edit this user?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    if (ubll.FullName.Equals("") == false && ubll.Account.Equals("") == false && ubll.Password.Equals("") == false && ubll.Address.Equals("") == false && ubll.Phone.Equals("") == false && ubll.Email.Equals("") == false)
                    {
                        if (check.IsAlphaNumeric(ubll.Account) && check.IsAlphaNumeric(ubll.Password) && ubll.Password.Length >= 4)
                        {
                            if (check.IsValidEmail(ubll.Email))
                            {
                                udal.editUser(ubll);
                                MessageBox.Show("An user have been edited successfully!");
                                userBiding();
                            }
                            else
                            {
                                MessageBox.Show("Email is invalid!");
                            }
                        }
                        else
                        {
                            MessageBox.Show("Account or Password is invalid!");
                        }
                    }
                    else
                    {
                        MessageBox.Show("You don't enter complete information!");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnUDelete_Click(object sender, EventArgs e)
        {
            udal = new UserDAL();
            ubll = new UserBLL();

            try
            {
                if (MessageBox.Show("You sure you want to delete this user?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    ubll.Account = txtAccount.Text;
                    udal.delUser(ubll);
                    MessageBox.Show("An user have been deleted successfully!");
                    userBiding();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnUReset_Click(object sender, EventArgs e)
        {
            txtFullName.Text = null;
            txtAccount.Text = null;
            txtPass.Text = null;
            txtAddress.Text = null;
            txtPhone.Text = null;
            txtEmail.Text = null;
        }

        private void btnTCreate_Click(object sender, EventArgs e)
        {
            tdal = new TheoriesDAL();
            tbll = new TheoriesBLL();

            try
            {
                tbll.Chapter = txtNumberChapter.Text;
                tbll.Name = txtNameChapter.Text;
                tbll.Description = txtTheoryDesc.Text; 

                if (tbll.Chapter.Equals("") == false && tbll.Name.Equals("") == false && tbll.Description.Equals("") == false)
                {
                    if (check.IsWholeNumber(tbll.Chapter))
                    {
                        tdal.addTheory(tbll);
                        MessageBox.Show("An theory have been created successfully!");
                        theoriesBiding();
                    }
                    else
                    {
                        MessageBox.Show("Chapter must is numbers!");
                    }            
                }
                else
                {
                    MessageBox.Show("You don't enter complete information!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnTUpdate_Click(object sender, EventArgs e)
        {
            tdal = new TheoriesDAL();
            tbll = new TheoriesBLL();

            try
            {
                tbll.Chapter = txtNumberChapter.Text;
                tbll.Name = txtNameChapter.Text;
                tbll.Description = txtTheoryDesc.Text; 

                if (MessageBox.Show("You sure you want to edit this user?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    if (tbll.Chapter.Equals("") == false && tbll.Name.Equals("") == false && tbll.Description.Equals("") == false)
                    {
                        tdal.editTheory(tbll);
                        MessageBox.Show("An theory have been edited successfully!");
                        theoriesBiding();
                    }
                    else
                    {
                        MessageBox.Show("You don't enter complete information!");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnTReset_Click(object sender, EventArgs e)
        {
            txtNumberChapter.Text = null;
            txtNumberChapter.ReadOnly = false;
            txtNameChapter.Text = null;
            txtTheoryDesc.Text = null;
        }

        private void btnQCreate_Click(object sender, EventArgs e)
        {
            qdal = new QuestionDAL();
            qbll = new QuestionBLL();

            try
            {
                qbll.Chapter = txtChooseChapter.Text;
                
                if (rbNQ.Checked)
                {
                    qbll.Type = 1;
                    qbll.Question = txtQuest.Text;
                    qbll.Answer = txtAnswer.Text;
                }
                if (rbMQ.Checked)
                {
                    qbll.Type = 2;
                    qbll.QuestionFile = txtQFile.Text;
                    qbll.AnswerFile = txtQAFile.Text;
                }
                qbll.Status = 0;
                qbll.Images = txtImage.Text;

                if (qbll.Chapter.Equals("") == false && qbll.Question.Equals("") == false && qbll.Answer.Equals("") == false)
                {
                    qdal.addQuestion(qbll);
                    MessageBox.Show("An question have been created successfully!");
                    questionBiding();
                }
                else
                {
                    MessageBox.Show("You don't enter complete information!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnQUpdate_Click(object sender, EventArgs e)
        {
            qdal = new QuestionDAL();
            qbll = new QuestionBLL();

            try
            {
                qbll.Chapter = txtChooseChapter.Text;
                qbll.QuestionId = Int32.Parse(txtQID.Text);
                qbll.Status = 0;
                qbll.Images = txtImage.Text;

                if (rbNQ.Checked)
                {
                    qbll.Type = 1;
                    qbll.Question = txtQuest.Text;
                    qbll.Answer = txtAnswer.Text;

                    if (qbll.Chapter.Equals("") == false && qbll.Question.Equals("") == false && qbll.Answer.Equals("") == false)
                    {
                        qdal.editQuestion(qbll);
                        MessageBox.Show("An question have been edited successfully!");
                        questionBiding();
                    }
                    else
                    {
                        MessageBox.Show("You don't enter complete information!");
                    }
                }
                if (rbMQ.Checked)
                {
                    qbll.Type = 2;
                    qbll.QuestionFile = txtQFile.Text;
                    qbll.AnswerFile = txtQAFile.Text;


                    if (qbll.QuestionFile.Equals("") == false && qbll.AnswerFile.Equals("") == false)
                    {
                        qdal.editQuestion(qbll);
                        MessageBox.Show("An question have been edited successfully!");
                        questionBiding();
                    }
                    else
                    {
                        MessageBox.Show("You don't enter complete information!");
                    }
                }

                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnQDelete_Click(object sender, EventArgs e)
        {
            qdal = new QuestionDAL();
            qbll = new QuestionBLL();

            try
            {
                if (MessageBox.Show("You sure you want to delete this question?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    qbll.QuestionId = Int32.Parse(txtQID.Text);
                    qdal.delQuestion(qbll);
                    MessageBox.Show("An question have been deleted successfully!");
                    questionBiding();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnQReset_Click(object sender, EventArgs e)
        {
            txtNumberChapter.Text = null;
            txtQuest.Text = null;
            txtAnswer.Text = null;
            txtQFile.Text = null;
            txtQAFile.Text = null;
            txtImage.Text = null;
            txtQID.Text = null;
        }

        private void txtChooseChapter_MouseClick(object sender, MouseEventArgs e)
        {
            ChooseChapter chooseChapter = new ChooseChapter(txtChooseChapter);
            chooseChapter.Show();
        }

        private void btnImage_Click(object sender, EventArgs e)
        {
            try
            {
                _openFileDialog.Title = "Open images file";
                _openFileDialog.InitialDirectory = @"C:\";//Thư mục mặc định khi mở
                _openFileDialog.Filter = "JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png|GIF (*.gif)|*.gif|All files (*.*)|*.*";// Lọc ra những file cần hiển thị
                _openFileDialog.RestoreDirectory = true;

                if (_openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string[] tmp = _openFileDialog.FileNames;

                    foreach (string i in tmp)
                    {
                        FileInfo fileInfo = new FileInfo(i);
                        string[] xxx = i.Split('\\');
                        string des = Application.StartupPath + @"\Files\Images\" + xxx[xxx.Length - 1];
                        File.Delete(des);

                        txtImage.Text = xxx[xxx.Length - 1];
                        fileInfo.CopyTo(des);
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void dgvUsers_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int currentRow = e.RowIndex;
            txtAccount.Text = dgvUsers[0, currentRow].Value.ToString();
            txtFullName.Text = dgvUsers[1, currentRow].Value.ToString();
            txtPass.Text = dgvUsers[2, currentRow].Value.ToString();
            txtEmail.Text = dgvUsers[3, currentRow].Value.ToString();
            txtPhone.Text = dgvUsers[4, currentRow].Value.ToString();
            txtAddress.Text = dgvUsers[5, currentRow].Value.ToString();
            if (dgvUsers[6, currentRow].Value.ToString() == "1")
            {
                cbxStatus.SelectedIndex = 0;
            }
            if (dgvUsers[6, currentRow].Value.ToString() == "2")
            {
                cbxStatus.SelectedIndex = 1;
            }
        }

        private void dgvTheories_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int currentRow = e.RowIndex;
            txtNumberChapter.Text = dgvTheories[0, currentRow].Value.ToString();
            txtNameChapter.Text = dgvTheories[1, currentRow].Value.ToString();
            txtTheoryDesc.Text = dgvTheories[2, currentRow].Value.ToString();
        }

        private void dgvQuestion_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int currentRow = e.RowIndex;
            txtQID.Text = dgvQuestion[0, currentRow].Value.ToString();
            txtChooseChapter.Text = dgvQuestion[1, currentRow].Value.ToString();
            if (dgvQuestion[7, currentRow].Value.ToString() == "1")
            {
                rbNQ.Checked = true;
                panelNQ.Visible = true;
                panelMQ.Visible = false;
                txtQuest.Text = dgvQuestion[2, currentRow].Value.ToString();
                txtAnswer.Text = dgvQuestion[3, currentRow].Value.ToString();
            }
            if (dgvQuestion[7, currentRow].Value.ToString() == "2")
            {
                rbMQ.Checked = true;
                panelMQ.Visible = true;
                txtQFile.Text = dgvQuestion[4, currentRow].Value.ToString();
                txtQAFile.Text = dgvQuestion[5, currentRow].Value.ToString();
            }
            txtImage.Text = dgvQuestion[6, currentRow].Value.ToString();
        }

        private void Management_Load(object sender, EventArgs e)
        {

        }

        private void GetData(string selectCommand)
        {
            DataTable dt = new DataTable();
            try
            {
                adapter = new SqlDataAdapter(selectCommand, DBConnect.getConnection());
                adapter.Fill(dt);
                bs.DataSource = dt;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void btnUSearch_Click(object sender, EventArgs e)
        {
            string type = null;
            string key = txtUSearch.Text;

            if (cbxUSearch.SelectedIndex == 0)
            {
                type = "Account";
            }
            else if (cbxUSearch.SelectedIndex == 1)
            {
                type = "FullName";
            }
            else if (cbxUSearch.SelectedIndex == 2)
            {
                type = "Email";
            }

            GetData("EXEC sp_searchUser '" + type + "', N'" + key + "'");
            dgvUsers.DataSource = bs;
            lblURecord.Text = dgvUsers.RowCount.ToString();
        }

        private void btnTSearch_Click(object sender, EventArgs e)
        {
            string key = txtTSearch.Text;

            GetData("EXEC sp_searchTheories N'" + key + "'");
            dgvTheories.DataSource = bs;
            lblTRecord.Text = dgvTheories.RowCount.ToString();
        }

        private void btnQSearch_Click(object sender, EventArgs e)
        {
            string key = cbxLoadChapter.SelectedValue.ToString();

            GetData("EXEC sp_searchQuestion N'" + key + "'");
            dgvQuestion.DataSource = bs;
            lblQRecord.Text = dgvQuestion.RowCount.ToString();
        }
    }
}
